package com.crois.barrier.web.configuration;

import com.alibaba.nacos.api.config.ConfigService;
import com.crois.barrier.web.cache.CacheManager;
import com.crois.barrier.web.cache.CommonPluginDataSubscriber;
import com.crois.barrier.web.cache.NacosSyncCache;
import com.crois.barrier.web.handler.MonitorPluginDataHandler;
import com.crois.barrier.web.handler.PluginDataHandler;
import com.crois.barrier.web.sync.PluginDataSubscriber;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import java.util.Collections;
import java.util.List;

/**
 * @author Hou Ze Yu
 * @description 缓存 同步 配置
 * @date 2020/7/13
 */
@AutoConfigureBefore(BarrierAutoConfiguration.class)
public class CacheConfiguration {

    /**
     * naocs 同步 缓存管理
     */
    @Configuration
    @ConditionalOnMissingBean(CacheManager.class)
    @Import(NacosConfigConfiguration.class)
    static class NacosCacheManager{

        @Bean
        public PluginDataHandler  monitorPluginDataHandler(){
            return new MonitorPluginDataHandler();
        }
        @Bean
        public PluginDataSubscriber commonPluginDataSubscriber(final ObjectProvider<List<PluginDataHandler>> pluginDataHandlerList){
            return new CommonPluginDataSubscriber(pluginDataHandlerList.getIfAvailable(Collections::emptyList));
        }
        /***
         * nacos缓存配置
         * @param configService
         * @return
         */
        @Bean
        public CacheManager localCacheManager(final ConfigService configService,PluginDataSubscriber pluginDataSubscriber){
            return new NacosSyncCache(configService,pluginDataSubscriber);
        }
    }
}
